﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

using Utils;

namespace System.Linq
{
    public static class IEnumerableHelper
    {
        private static Random _random = new Random();
#if NETCOREAPP3_1
        /// <summary>
        /// 差集
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <typeparam name="KEY"></typeparam>
        /// <param name="first"></param>
        /// <param name="second"></param>
        /// <param name="commp"></param>
        /// <returns></returns>
        public static IEnumerable<T> ExceptBy<T, KEY>(this IEnumerable<T> first, IEnumerable<T> second, Func<T, KEY> commp)
        {
            return first.Except(second, new DefaultEqualityComparer<T, KEY>(commp));
        }
        /// <summary>
        /// 并集
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <typeparam name="KEY"></typeparam>
        /// <param name="first"></param>
        /// <param name="second"></param>
        /// <param name="commp"></param>
        /// <returns></returns>
        public static IEnumerable<T> UnionBy<T, KEY>(this IEnumerable<T> first, IEnumerable<T> second, Func<T, KEY> commp)
        {
            return first.Union(second, new DefaultEqualityComparer<T, KEY>(commp));
        }
        /// <summary>
        /// 交集
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <typeparam name="KEY"></typeparam>
        /// <param name="first"></param>
        /// <param name="second"></param>
        /// <param name="commp"></param>
        /// <returns></returns>
        public static IEnumerable<T> IntersectBy<T, KEY>(this IEnumerable<T> first, IEnumerable<T> second, Func<T, KEY> commp)
        {
            return first.Intersect(second, new DefaultEqualityComparer<T, KEY>(commp));
        }

        /// <summary>
        /// 去重
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <typeparam name="KEY"></typeparam>
        /// <param name="first"></param>
        /// <param name="commp"></param>
        /// <returns></returns>
        public static IEnumerable<T> DistinctBy<T, KEY>(this IEnumerable<T> first, Func<T, KEY> commp)
        {
            return first.Distinct(new DefaultEqualityComparer<T, KEY>(commp));
        }
#endif
        /// <summary>
        /// 分段
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        /// <param name="size"></param>
        /// <returns></returns>
        public static IEnumerable<IEnumerable<T>> Split<T>(this IEnumerable<T> list, int size)
        {
            int count = list.Count();
            for (int i = 0; i < count; i += size)
            {
                yield return list.Skip(i).Take(size);
            }
        }

        /// <summary>
        /// 数组遍历
        /// </summary>
        /// <param name="end"></param>
        /// <returns></returns>
        public static IEnumerable<int> Range(this int end)
        {
            for (int i = 0; i < end; i++)
            {
                yield return i;
            }
            yield break;
        }

        public static IEnumerable<int> Range(this int start, int end)
        {
            for (int i = start; i < end; i++)
            {
                yield return i;
            }
            yield break;
        }


        public static void FirstIfPresent<T>(this IEnumerable<T> list, Action<T> action)
        {
            if (list.Count() > 0)
            {
                action(list.First());
            }
        }


        public static T Random<T>(this IEnumerable<T> list)
        {
            var array = list.ToArray();
            return array[_random.Next(array.Length)];
        }


        public static async Task<List<T>> ToTaskList<T>(this IAsyncEnumerable<T> list)
        {
            List<T> result = new List<T>();
            await foreach (var item in list)
            {
                result.Add(item);
            }
            return result;
        }
        /// <summary>
        /// 集合中是否包含满足条件的某项
        /// </summary>
        /// <typeparam name="T">集合元素类型</typeparam>
        /// <param name="list">集合对象</param>
        /// <param name="predicate">判定条件</param>
        /// <returns>是否存在</returns>
        /// <example>
        /// <code lang="c#">
        /// <![CDATA[
        ///     List<string> list={"1","3","5","7"};
        ///     
        ///     bool ret=list.Contains(c=>c=="3");  //True
        /// ]]>
        /// </code>
        /// </example>
        public static bool Contains<T>(this IEnumerable<T> list, Predicate<T> predicate)
        {
            return list.Any(item => predicate(item));
        }

        /// <summary>
        /// 对IEnumerable&lt;T&gt;的每个元素执行指定操作
        /// </summary>
        /// <typeparam name="T">集合元素类型</typeparam>
        /// <param name="list">集合对象</param>
        /// <param name="action">要执行的操作</param>
        /// <example>
        /// <code lang="c#">
        /// <![CDATA[
        ///     string[] list={"1","3","5","7"};
        ///     list.ForEach(c=>{
        ///         Response.Write(c);
        ///     });
        /// ]]>
        /// </code>
        /// </example>
        public static void ForEach<T>(this IEnumerable<T> list, Action<T> action)
        {
            foreach (T item in list)
            {
                action(item);
            }
        }

        public static void ForEach<T>(this IEnumerable<T> list, Action<T, int> action)
        {
            int i = 0;
            foreach (T item in list)
            {
                action(item, i);
                i++;
            }
        }

        public static IEnumerable<T> TrueThrow<T>(this IEnumerable<T> list, Predicate<T> predicate, Func<T, Exception> funcException)
        {
            foreach (T item in list)
            {
                if (predicate(item))
                {
                    throw funcException(item);
                }
            }
            return list;
        }

        public static List<T> Recursion<T, K>(this IEnumerable<T> all, Func<T, K> currentKey, Func<T, K> parentKey, K rootKey = default) where T : Recursion<T> where K : IEquatable<K>
        {
            return all.Recursion(currentKey, parentKey, item =>
            {
                var pk = parentKey(item);
                return pk == null || pk.Equals(rootKey);
            });
        }
        /// <summary>
        /// 递归算法
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <typeparam name="K"></typeparam>
        /// <param name="all"></param>
        /// <param name="parentFunc"></param>
        /// <param name="childrenFunc"></param>
        /// <param name="isRoot"></param>
        /// <returns></returns>
        public static List<T> Recursion<T, K>(this IEnumerable<T> all, Func<T, K> currentKey, Func<T, K> parentKey, Func<T, bool> isRoot) where T : Recursion<T> where K : IEquatable<K>
        {

            List<T> tree = new List<T>();
            Dictionary<K, T> nodes = all.ToDictionary(currentKey);
            all.ForEach(item =>
            {
                K pk = parentKey(item);
                K ck = currentKey(item);
                if (isRoot(item))
                {
                    tree.Add(item);
                }
                else if (nodes.ContainsKey(pk))
                {
                    T node = nodes[pk];
                    if (node.Children == null)
                        node.Children = new List<T>();
                    node.Children.Add(item);
                }
            });
            return tree;
        }

        public static List<O> ToTree<T, O, K>(this IEnumerable<T> current, Func<T, K> currentKey, Func<T, K> parentKey, Func<T, O> conversion, K rootKey = default)
            where O : Recursion<O> where K : IEquatable<K>
        {
            return current.ToTree(currentKey, parentKey, conversion, item =>
          {
              var pk = parentKey(item);
              return pk == null || pk.Equals(rootKey);
          });
        }
        /// <summary>
        /// 转为树结构
        /// </summary>
        /// <param name="current"></param>
        /// <param name="conversion"></param>
        /// <param name="currentKey"></param>
        /// <param name="parentKey"></param>
        /// <param name="rootKey"></param>
        /// <returns></returns>
        public static List<O> ToTree<T, O, K>(this IEnumerable<T> current, Func<T, K> currentKey, Func<T, K> parentKey, Func<T, O> conversion, Func<T, bool> isRoot)
        where O : Recursion<O> where K : IEquatable<K>
        {
            List<O> tree = new List<O>();
            Dictionary<K, (K, O, T)> nodes = current.ToDictionary(currentKey, item => (parentKey(item), conversion(item), item));

            nodes.ForEach(item =>
            {
                K pk = item.Value.Item1;
                K ck = item.Key;
                if (isRoot(item.Value.Item3))
                {
                    tree.Add(item.Value.Item2);
                }
                else if (nodes.ContainsKey(pk))
                {
                    O node = nodes[pk].Item2;
                    if (node.Children == null)
                        node.Children = new List<O>();
                    node.Children.Add(item.Value.Item2);
                }

            });
            return tree;
        }
        /// <summary>
        ///  在指定  IEnumerable`T 的每个元素之间串联指定的分隔符 System.String，从而产生单个串联的字符串。
        /// </summary>
        /// <typeparam name="T">集合元素类型</typeparam>
        /// <param name="list">集合对象</param>
        /// <param name="toText">将T转换为文本</param>
        /// <param name="separator">分隔符</param>
        /// <returns>拼接字符串</returns>
        /// <example>
        /// <code lang="c#">
        /// <![CDATA[
        ///     List<DateTime> list=new List<DateTime>();
        ///     
        ///     string ret=list.Join(d=>d.ToString("yyyyMMdd"),",");
        /// 
        /// ]]>
        /// </code>
        /// </example>
        public static string Join<T>(this IEnumerable<T> list, Func<T, string> toText, string separator)
        {
            if (list == null)
                return null;

            StringBuilder sb = new StringBuilder();
            var enumtor = list.GetEnumerator();
            if (enumtor.MoveNext())
            {
                sb.Append(toText(enumtor.Current));
                while (enumtor.MoveNext())
                {
                    sb.Append(separator);
                    sb.Append(toText(enumtor.Current));
                }
            }

            return sb.ToString();
        }


        /// <summary>
        /// 在指定  IEnumerable`T 的每个元素之间串联指定的分隔符 System.String，从而产生单个串联的字符串。
        /// </summary>
        /// <typeparam name="T">集合元素类型</typeparam>
        /// <param name="list">集合对象</param>
        /// <param name="separator">分割字符</param>
        /// <returns>拼接字符串</returns>
        /// <example>
        /// <code lang="c#">
        /// <![CDATA[
        ///     int[] ary={1,2,3,4,5};
        ///     
        ///     string str=ary.Join();  //返回："1,2,3,4,5"
        /// ]]>
        /// </code>
        /// </example>
        public static string Join<T>(this IEnumerable<T> list, string separator = ",")
        {
            if (list == null)
                return null;

            return list.Join((T v) => v.ToString(), separator);
        }



        public static void PaddingName<T, K, V>(this List<T> list, Func<K[], Dictionary<K, V>> createDict, Func<T, K> from, Expression<Func<T, V>> selector)
        {
            if (list.Count == 0) return;
            var dict = createDict(list.Select(from).ToArray());
            PropertyInfo info = (selector.Body as MemberExpression).Member as PropertyInfo;
            foreach (var item in list)
            {
                info.SetValue(item, dict.TryGetValue(from(item), default));
            }
        }
    }

    public interface Recursion<T>
    {
        List<T> Children { get; set; }

    }
}
